package weixin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;


public class HttpUtil {

	public static String httpReauest(String rqRrl){
		HttpURLConnection con = null;
		try {
			URL url = new URL(rqRrl);
			con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("POST");
			con.setRequestProperty("contentType", "UTF-8");  
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
			
			String line,returnjson = null;
			while ((line = in.readLine()) != null) {
				returnjson +=line;
			}
			return returnjson;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static String httpReauest(String rqRrl,String xml) throws Exception{
		try {
			TrustManager[] tm = {new MyX509TrustManager()};
		        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		        sslContext.init(null, tm, new java.security.SecureRandom());
		        // 从上述SSLContext对象中得到SSLSocketFactory对象
		        SSLSocketFactory ssf = sslContext.getSocketFactory();
		        // 创建URL对象
		        URL myURL = new URL(rqRrl);
		        // 创建HttpsURLConnection对象，并设置其SSLSocketFactory对象
		        HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection();
		        httpsConn.setSSLSocketFactory(ssf);
		        httpsConn.setRequestMethod("POST");
		        httpsConn.setRequestProperty("contentType", "UTF-8");  
		        httpsConn.setDoOutput(true);
			OutputStream outputStream = httpsConn.getOutputStream();
			outputStream.write(xml.getBytes());
			outputStream.flush();outputStream.close();
			
			BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream())); 
			
			String line,returnjson = null;
			while ((line = in.readLine()) != null) {
				returnjson +=line;
			}
			return returnjson;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	public static String httpsReauest(String rqRrl,String xml){
		HttpsURLConnection con = null;
		try {
			URL url = new URL(rqRrl);
			con = (HttpsURLConnection) url.openConnection();
			con.setRequestMethod("POST");
			con.setRequestProperty("contentType", "UTF-8");  
			con.setDoOutput(true);
			OutputStream outputStream = con.getOutputStream();
			outputStream.write(xml.getBytes());
			outputStream.flush();outputStream.close();
			
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
			
			String line,returnjson = null;
			while ((line = in.readLine()) != null) {
				returnjson +=line;
			}
			return returnjson;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
